package com.marion.study.aop;

import com.marion.study.service.AuthService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AdminAspect {

    @Autowired
    private AuthService authService;

    /**
     * 1. 定义切面表达式
     * 2. 前置的的校验
     */
    @Pointcut(value = "@annotation(AdminOnly)")
//    @Pointcut(value = "@within(com.marion.study.service.*)")
//    @Pointcut(value = "@within(com.marion.study.service.*)")
    private void auth() {

    }

    /**
     * 2. Advice注解
     */
    @Before("auth()")
    public void before() {
        System.out.println("[before] before ...");

        if (!authService.isLogin(1)) {
            throw new NullPointerException("user not login");
        }

    }

    /**
     * 2. 后置打印
     */
    @After("auth()")
    public void after() {
        System.out.println("[after] after ...");
    }

    /**
     * 3. 环绕通知
     */
    @Around("auth()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        System.out.println("[around] before ...");

        try {
            return point.proceed(point.getArgs());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw throwable;
        } finally {
            System.out.println("[around] after ...");
        }

    }

}
